package ar.com.photo_admin.domain

import org.springframework.dao.DataIntegrityViolationException
import grails.converters.*;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

class AlbumController {

	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

					
	def index() {
		redirect(action: "list", params: params)
	}

	def list() {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[albumInstanceList: Album.list(params), albumInstanceTotal: Album.count()]
	}

	def create() {
		[albumInstance: new Album(params)]
	}
	
	def create_album() {
		println("ENTRO!")
		println("ENTRO!")
		println  "Receive send request";
		def contentType = request.getHeader('Content-Type')
		println  "receive with ContentType: " + contentType;
		
		if (contentType && contentType.contains('application/json')) {            
			def results = request.JSON
			println "results received : ${results}"
		}
	}

	def save() {
		def albumInstance = new Album(params)
		if (!albumInstance.save(flush: true)) {
			render(view: "create", model: [albumInstance: albumInstance])
			return
		}

		flash.message = message(code: 'default.created.message', args: [
			message(code: 'album.label', default: 'Album'),
			albumInstance.id
		])
		redirect(action: "show", id: albumInstance.id)
	}

	def upload() {
		
		//Collection que almacena el resultado de todos las fotos recibidas.
		Collection results = []
		
		//Mapa que almacena las propiedades de cada foto.
		def result = [:]
 
		//TODO Por alguna razon llegan requests con content type nulo. 
		if (request.getContentType() != null){
			
			DefaultMultipartHttpServletRequest filesRequest = (DefaultMultipartHttpServletRequest) request
			
			Iterator itr = filesRequest.getFileNames();

			def photoDir;
			
			while(itr.hasNext()) {
				def file = filesRequest.getFile(itr.next()); 
	
				if (!file.isEmpty()) {	
					
					
					photoDir = IMAGES_PATH+file.getOriginalFilename()
					File destination = new File(photoDir)
					file.transferTo(destination)
					
					
					result['name'] = file.getOriginalFilename()
					result['size']= destination.size()									
					result['type']= file.getContentType()
					
					
					def validationResult = validateFile(result)
					
					if (validationResult){
						result['delete_type'] = 'DELETE'
						result['url'] = SERVER_PATH + result['name'] 
						//result['thumbnail_url'] = result['url'] + THUMBNAIL_MODIFICATOR												
					}
					
					results << result
					
				
				}
				else {
					log.error("El archivo no pudo ser copiado")
				}
			}
		}

		//Devuelvo un mapa en formato JSON con los resultados.
		render results as JSON
	}
	
	def validateFile(def result){
		if (result['size'] < MIN_FILE_SIZE)
			result['error'] = 'minFileSize'
		else if (result['size'] > MAX_FILE_SIZE)
			result['error'] = 'maxFileSize'
		else if (! ACCEPT_FILE_TYPES.contains(result['type']))
			result['error'] = 'acceptFileTypes'
		else
			return true
		return false
	}

	def show() {
		def albumInstance = Album.get(params.id)
		if (!albumInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[albumInstance: albumInstance]
	}

	def edit() {
		def albumInstance = Album.get(params.id)
		if (!albumInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[albumInstance: albumInstance]
	}

	def update() {
		def albumInstance = Album.get(params.id)
		if (!albumInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "list")
			return
		}

		if (params.version) {
			def version = params.version.toLong()
			if (albumInstance.version > version) {
				albumInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
						[
							message(code: 'album.label', default: 'Album')]
						as Object[],
						"Another user has updated this Album while you were editing")
				render(view: "edit", model: [albumInstance: albumInstance])
				return
			}
		}

		albumInstance.properties = params

		if (!albumInstance.save(flush: true)) {
			render(view: "edit", model: [albumInstance: albumInstance])
			return
		}

		flash.message = message(code: 'default.updated.message', args: [
			message(code: 'album.label', default: 'Album'),
			albumInstance.id
		])
		redirect(action: "show", id: albumInstance.id)
	}

	def delete() {
		def albumInstance = Album.get(params.id)
		if (!albumInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "list")
			return
		}

		try {
			albumInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "list")
		}
		catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [
				message(code: 'album.label', default: 'Album'),
				params.id
			])
			redirect(action: "show", id: params.id)
		}
	}
}
